package com.lefu.es.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

/**
 * 图片工具类
 *
 * @author Leon
 *         2015-11-19
 */
public class ImageUtil {
    private static final String TAG = "ImageUtil";

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public static String saveBitmap(String savePath, String picName, Bitmap bm) {
        String photoUrl = "";
        if (null == savePath || null == picName || null == bm) {
            return photoUrl;
        }
        File file = new File(savePath);
        if (!file.exists()) {// 如果目录不存在就创建目录
            file.mkdirs();
        }
        try {
            photoUrl = compressPicture(bm, savePath + picName);
            LogUtils.i(TAG, "==========图片保存的url:" + photoUrl);
            FileOutputStream out = new FileOutputStream(savePath + picName);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            photoUrl = savePath + picName;
            out.flush();
            out.close();
            Log.i(TAG, "已经保存");
        } catch (Exception e) {
            Log.i(TAG, "保存失败:" + e.getMessage());
            photoUrl = "";
        }
        return photoUrl;
    }

    public static String compressPicture(Bitmap bitmap, String imageurl) {
        FileOutputStream fos;
        BitmapFactory.Options op = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        op.inJustDecodeBounds = true;
        op.inJustDecodeBounds = false;
        // 缩放图片的尺寸
        float w = op.outWidth;
        float h = op.outHeight;
        float hh = 160f;//
        float ww = 160f;//
        // 最长宽度或高度1024
        float be = 1.0f;
        if (w > h && w > ww) {
            be = w / ww;
        } else if (w < h && h > hh) {
            be = h / hh;
        }
        if (be <= 0) {
            be = 1.0f;
        }
        op.inSampleSize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小.
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        int desWidth = (int) (w / be);
        int desHeight = (int) (h / be);
        bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
        try {
            fos = new FileOutputStream(imageurl);
            if (bitmap != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            }
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return imageurl;
        }
    }


    public static String compressPicture1(String srcPath) {
        FileOutputStream fos;
        BitmapFactory.Options op = new BitmapFactory.Options();

        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        op.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
        op.inJustDecodeBounds = false;

        // 缩放图片的尺寸
        float w = op.outWidth;
        float h = op.outHeight;
        float hh = 320f;//
        float ww = 320f;//
        // 最长宽度或高度1024
        float be = 2.0f;
        if (w > h && w > ww) {
            be = w / ww;
        } else if (w < h && h > hh) {
            be = h / hh;
        }
        if (be <= 0) {
            be = 1.0f;
        }
        op.inSampleSize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小.
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, op);
        int desWidth = (int) (w / be);
        int desHeight = (int) (h / be);
        bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
        try {
            fos = new FileOutputStream(srcPath);
            if (bitmap != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            }
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return srcPath;
        }

    }

    public Bitmap getBitmapTodifferencePath(String path, Context context) {
        if (path.length() < 7) {
            return null;
        }
        String str = path.substring(0, 7);
        if ("content".equals(str)) {
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;

                BitmapFactory.decodeStream(context.getContentResolver().openInputStream(Uri.parse(path)), null, options);

                int height = options.outHeight;

                if (options.outWidth > 100) {
                    options.inSampleSize = options.outWidth / 100 + 1 + 1;
                    options.outWidth = 100;
                    height = options.outHeight / options.inSampleSize;
                    options.outHeight = height;
                }
                options.inJustDecodeBounds = false;
                options.inPurgeable = true;
                options.inInputShareable = true;

                return BitmapFactory.decodeStream(context.getContentResolver().openInputStream(Uri.parse(path)), null, options);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);

            int height = options.outHeight;
            if (options.outWidth > 100) {
                options.inSampleSize = options.outWidth / 100 + 1 + 1;
                options.outWidth = 100;
                height = options.outHeight / options.inSampleSize;
                options.outHeight = height;
            }
            options.inJustDecodeBounds = false;
            options.inPurgeable = true;
            options.inInputShareable = true;
            return BitmapFactory.decodeFile(path, options);
        }

        return null;
    }

   public static Bitmap drawableToBitmap(Drawable drawable) // drawable 转换成bitmap
    {
        int width = drawable.getIntrinsicWidth();// 取drawable的长宽
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;// 取drawable的颜色格式
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);// 建立对应bitmap
        Canvas canvas = new Canvas(bitmap);// 建立对应bitmap的画布
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);// 把drawable内容画到画布中
        return bitmap;
    }

}
